/* Copyright (c) 2006, 2009, Carl Burch. License information is located in the
 * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */
 
package com.cburch.draw.model;

import java.awt.Graphics;
import java.util.List;

import com.cburch.logisim.data.Attribute;
import com.cburch.logisim.data.Location;
import com.cburch.logisim.util.IntegerFactory;
import com.cburch.logisim.util.Strings;

class RoundRectangle extends Rectangular {
    private int radius;
    
    public RoundRectangle(int x, int y, int w, int h) {
        super(x, y, w, h);
        this.radius = 10;
    }
    
    public String getDisplayName() {
        return Strings.get("shapeRoundRect", Strings.drawSource);
    }
    
    public List getAttributes() {
        return DrawingAttribute.ATTRS_ROUND_RECT;
    }
    
    public Object getValue(Attribute attr) {
        if(attr == DrawingAttribute.CORNER_RADIUS) {
            return IntegerFactory.create(radius);
        } else {
            return super.getValue(attr);
        }
    }

    public void setAttrValue(Attribute attr, Object value) {
        if(attr == DrawingAttribute.CORNER_RADIUS) {
            radius = ((Integer) value).intValue();
        } else {
            super.setAttrValue(attr, value);
        }
    }
    
    protected boolean contains(int x, int y, int w, int h, Location q) {
        int qx = q.getX();
        int qy = q.getY();
        int r = radius + getStrokeWidth() / 2;
        if(qx >= x && qx < x + w && qy >= y && qy < y + h) {
            if(qx < x + r) {
                if(qy < y + r) return inCircle(qx, qy, x + r, y + r, r);
                else if(qy < y + h - r) return true;
                else return inCircle(qx, qy, x + r, y + h - r, r);
            } else if(qx < x + w - r) {
                return true;
            } else {
                if(qy < y + r) return inCircle(qx, qy, x + w - r, y + r, r);
                else if(qy < y + h - r) return true;
                else return inCircle(qx, qy, x + w - r, y + h - r, r);
            }
        } else {
            return false;
        }
    }
    
    private static boolean inCircle(int qx, int qy, int cx, int cy, int r) {
        int dx = qx - cx;
        int dy = qy - cy;
        return dx * dx + dy * dy < r * r;
    }
    
    public void draw(Graphics g, int x, int y, int w, int h) {
        int diam = 2 * radius;
        if(setForFill(g)) g.fillRoundRect(x, y, w, h, diam, diam);
        if(setForStroke(g)) g.drawRoundRect(x, y, w, h, diam, diam);
    }
}
